import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:dio_http_cache/dio_http_cache.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base/route/auth_guard.dart';
import 'package:flutter_base/route/router.gr.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_picker/PickerLocalizationsDelegate.dart';
import 'package:provider/provider.dart';

import 'package:flutter_base/core/toast.dart';
import 'package:flutter_base/const/app_servers.dart';
import 'package:flutter_base/utils/app_utils.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'core/core_kit.dart';
import 'core/http/dior.dart';
import 'const/app_theme.dart';
import 'generated/l10n.dart';

void main() {
  // 启用网络请求输出
  HttpClient.enableTimelineLogging = kDebugMode;

  WidgetsFlutterBinding.ensureInitialized();

  runApp(App());
}

class App extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return AppState();
  }
}

class AppState extends State<App> {
  final _httpCacheManager = DioCacheManager(CacheConfig(
    baseUrl: AppServers.baseUrl,
    encrypt: (encrypt) async {
      return AppUtils.encryptBytes(encrypt);
    },
    decrypt: (decrypt) async {
      return AppUtils.decryptBytes(decrypt);
    },
  ));

  final _eventBus = EventBus();

  // final _userProvider = SugarParkUserProvider();
  // final _profileProvider = KimProfileProvider();
  // final _conversationProvider = KimConversationsProvider();

  @override
  void initState() {
    super.initState();

    _configureHeyTeaKit();
    Dior.appDio.interceptors.add(_httpCacheManager.interceptor);
    // _userProvider.addListener(_onUserChanged);
    //
    // // 初始化IM SDK
    // KimClient().addConnectionListener(this);
    // KimLocalNotificationManager().register();
  }

  @override
  void dispose() {
    super.dispose();

    Dior.appDio.interceptors.remove(_httpCacheManager.interceptor);
    // _userProvider.removeListener(_onUserChanged);
    //
    // KimClient().removeConnectionListener(this);
    // KimLocalNotificationManager().unregister();
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        Provider.value(value: _eventBus),
        Provider.value(value: _httpCacheManager),
        // ChangeNotifierProvider.value(value: _userProvider),
        // ChangeNotifierProvider.value(value: _profileProvider),
        // ChangeNotifierProvider.value(value: _conversationProvider),
      ],
      child: MaterialApp(
        builder: (context, child) {
          child = ExtendedNavigator<AppRouter>(
            router: AppRouter(),
            guards: [AuthGuard()],
            observers: [CoreKitToastNavigatorObserver()],
            key: GlobalObjectKey(child.key),
          );

          child = Material(child: child);
          return CoreKitToastInit()(context, child);
        },
        darkTheme: appThemeData(Brightness.dark),
        debugShowCheckedModeBanner: true,
        localizationsDelegates: [
          GlobalCupertinoLocalizations.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          PickerLocalizationsDelegate.delegate,
          RefreshLocalizations.delegate,
          AppS.delegate,
        ],
        onGenerateRoute: AppRouter(),
        supportedLocales: AppS.delegate.supportedLocales,
        theme: appThemeData(Brightness.light),
        title: 'Flutter App Base',
      ),
    );
  }

  // @override
  // void onConnected() {
  //   BFKitLogger().d('Kim connected');
  // }
  //
  // @override
  // void onDisconnected(int errorCode) {
  //   BFKitLogger().d('Kim disconnected, errorCode: $errorCode');
  // }

  // void _onUserChanged() {
  //   _configureHeyTeaKit();
  //   // _conversationProvider.clear();
  // }

  void _configureHeyTeaKit() {
    // final user = _userProvider.value;
    // 初始化HeyTeaKit
    CoreKit.config = CoreKitConfig(
      apiBaseUrlsGetter: Future.value([AppServers.baseUrl]),
      apiHeadersGenerator: () async {
        final Map<String, dynamic> headers = {
          'platformType': Platform.operatingSystem,
          'version': '1.0',
        };

        // final token = user?.token;
        // final userId = user?.info?.id;
        //
        // if (token?.isNotEmpty == true) {
        //   headers['X-Access-Token'] = token;
        // }
        // if (userId?.isNotEmpty == true) {
        //   headers['userId'] = userId;
        // }

        return headers;
      }(),
    );
  }
}
